﻿#define _CRT_SECURE_NO_WARNINGS
#include"Tree.h"
#include"queue.h"
//前序遍历
void preOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	printf("%c ", root->data);
	preOrder(root->left);
	preOrder(root->right);
}

//中序遍历
void inOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	inOrder(root->left);
	printf("%c ", root->data);
	inOrder(root->right);
}

//后序遍历
void postOrder(BTNode* root)
{
	if (root == NULL)
	{
		printf("NULL ");
		return;
	}
	postOrder(root->left);
	postOrder(root->right);
	printf("%c ", root->data);
}

// ⼆叉树结点个数
int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);;
}
//int BinaryTreeSize(BTNode* root, int* psize)
//{
//	if (root == NULL)
//	{
//		return 0;
//	}
//	(*psize)++;//可以实现计数的功能，这个与static int size 有一样的效果，但是每次调用要手动置零。不方便
//	BinaryTreeSize(root->left, psize);
//	BinaryTreeSize(root->right, psize);
//	return *psize;
//}
//int BinaryTreeSize(BTNode* root)
//{
//	if (root == NULL)
//	{
//		return 0;
//	}
//	static int size = 0;
//	size++;
//	BinaryTreeSize(root->left);
//	BinaryTreeSize(root->right);
//	return size;
//}

// ⼆叉树叶⼦结点个数
int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	int left = BinaryTreeLeafSize(root->left);
	int right = BinaryTreeLeafSize(root->right);
	if (left == 0 && right == 0)
	{
		return 1;
	}
	return  left + right;
	/*与上面一致
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	return BinaryTreeLeafSize(root->left)
		+ BinaryTreeLeafSize(root->right);
	*/
}

// ⼆叉树第k层结点个数
int BinaryTreeLevelKSize(BTNode* root, int k)
{
	if (root == NULL)
	{
		return 0;
	}
	if (k == 1)
	{
		return 1;
	}
	return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
}

//⼆叉树的深度/⾼度
int BinaryTreeDepth(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	int lefthigh = BinaryTreeDepth(root->left);
	int righthigh = BinaryTreeDepth(root->right);
	return 1 + (lefthigh > righthigh ? lefthigh : righthigh);
}

// ⼆叉树查找值为x的结点
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
	if (root == NULL)
	{
		return NULL;
	}
	if (root->data==x)
	{
		return root;
	}
	if (BinaryTreeFind(root->left, x))
	{
		return root->left;
	}
	if (BinaryTreeFind(root->right, x))
	{
		return root->right;
	}
	return NULL;
}

// ⼆叉树销毁
void BinaryTreeDestory(BTNode** root)
{
	if (*root == NULL)
	{
		return;
	}
	BinaryTreeDestory(&((*root)->left));
	BinaryTreeDestory(&((*root)->right));
	free(*root);
	*root = NULL;
}

//层序遍历
void leverOrder(BTNode* root)
{
	Queue p;
	QueueInit(&p);
	QueuePush(&p, root);
	while (!QueueEmpty(&p))
	{
		BTNode* top = QueueFront(&p);//取队头
		QueuePop(&p);//出队头
		printf("%c ", top->data);
		//将队头非空左右孩子入队列
		if(top->left)
			QueuePush(&p, top->left);
		if(top->right)
			QueuePush(&p, top->right);
	}
	QueueDestroy(&p);
}